package com.wolfalpha.utron.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormal3Activity;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.service.UserService;
import com.wolfalpha.utron.service.impl.UserServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.CityAlertDialog;
import com.wolfalpha.utron.view.ListAlertDialog;
import com.wolfalpha.utron.view.SchoolAlertDialog;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人基本信息编辑界面
 * <p/>
 * Created by luodon on 15/8/21.
 */
public class UserEditActivity extends BaseNormal3Activity implements View.OnClickListener {

    private CheckBox cbBm;      //性别保密
    private CheckBox cbMan;     //男
    private CheckBox cbMale;    //女

    private EditText etNick;    //昵称
    private TextView etAge;     //年龄
    private TextView etSchool;  //学校
    private EditText etMail;    //邮箱
    private TextView etHome;    //故乡
    private EditText etSign;    //签名
    private EditText etIntro;   //个人简介

    private UserInfo userInfo;  //用户信息
    private int l_sex;          //z最新的性别

    private Map<String, Long> keyTimes = new HashMap<>();      //点击时间记录

    private ProgressDialog pd;

    private UserService userService;
    private int age = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((userInfo = AppContext.getInstance().getUserInfo()) == null) {
            UIHelper.showActivityAndFinish(UserEditActivity.this, LoginActivity.class);
            return;
        }
        setContentView(R.layout.activity_user_edit);

        userService = new UserServiceImpl();

        initView();
        initListeners();
        loadData();

        pd = new ProgressDialog(this);
        pd.setMessage("正在更新...");
    }

    /**
     * 加载数据
     */
    private void loadData() {
        if (userInfo.getNickname() != null) {
            etNick.setText(userInfo.getNickname());
        }
        if (userInfo.getUtron_sign() != null) {
            etSign.setText(userInfo.getUtron_sign());
        }
        if (userInfo.getIntroduction() != null) {
            etIntro.setText(userInfo.getIntroduction());
        }
        if (userInfo.getMail() != null) {
            etMail.setText(userInfo.getMail());
        }
        if (userInfo.getIntroduction() != null) {
            etIntro.setText(userInfo.getIntroduction());
        }
        if (userInfo.getSchool() != null) {
            etSchool.setText(userInfo.getIntroduction());
        }
        final String[] arr = this.getResources().getStringArray(R.array.user_age_years);
        int age = userInfo.getAge();
        if (age < 0 || age > arr.length) {
            etAge.setText("");
        } else {
            etAge.setText(arr[age]);
            if (age == 0 || age == arr.length - 1) {
                etAge.setText(arr[0]);
            } else {
                etAge.setText(31 - age + "");
            }
        }
        if (userInfo.getHome() != null) {
            etHome.setText(userInfo.getHome());
        }
        checkSex(l_sex = userInfo.getSex());
    }

    /**
     * 选择性别
     *
     * @param sex
     */
    private void checkSex(int sex) {
        if (sex == 0) {
            //保密
            cbBm.setChecked(true);
            cbMale.setChecked(false);
            cbMan.setChecked(false);
            l_sex = 0;
        }
        if (sex == 1) {
            //女生
            cbBm.setChecked(false);
            cbMale.setChecked(true);
            cbMan.setChecked(false);
            l_sex = 1;
        }
        if (sex == 2) {
            //男
            cbBm.setChecked(false);
            cbMale.setChecked(false);
            cbMan.setChecked(true);
            l_sex = 2;
        }
    }


    /**
     * 获取修改后的信息
     *
     * @return
     */
    private UserInfo getUserInfo() {
        UserInfo userInfo1 = userInfo;
        userInfo1.setSex(l_sex);
        if (TextUtils.isEmpty(etNick.getText().toString().trim())) {
            UIHelper.ToastMessage(UserEditActivity.this, "用户昵称不能为空");
            return null;
        } else {
            userInfo1.setNickname(etNick.getText().toString().trim());
        }
        if (TextUtils.isEmpty(etSign.getText().toString().trim())) {
            UIHelper.ToastMessage(UserEditActivity.this, "用户签名不能为空");
            return null;
        } else {
            userInfo1.setUtron_sign(etSign.getText().toString().trim());
        }
        if (!TextUtils.isEmpty(etMail.getText().toString().trim())) {
            if (!StringUtils.isEmail(etMail.getText().toString().trim())) {
                UIHelper.ToastMessage(UserEditActivity.this, "邮箱格式错误");
                return null;
            }
            userInfo1.setMail(etMail.getText().toString().trim());
        }
        if (!TextUtils.isEmpty(etIntro.getText().toString().trim())) {
            userInfo1.setIntroduction(etIntro.getText().toString().trim());
        }
        if (!TextUtils.isEmpty(etSchool.getText().toString().trim())) {
            userInfo1.setSchool(etSchool.getText().toString().trim());
        }
        if (!TextUtils.isEmpty(etHome.getText().toString().trim())) {
            userInfo1.setHome(etHome.getText().toString().trim());
        }

        userInfo1.setAge(age);

        return userInfo1;
    }

    private final int SUCCESS = 1;
    private final int FAIL = 2;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    AppContext.getInstance().saveObject(userInfo, "userInfo");
                    pd.dismiss();
                    UIHelper.ToastMessage(UserEditActivity.this, "更新成功");
                    finish();
                    break;
                case FAIL:
                    pd.dismiss();
                    UIHelper.ToastMessage(UserEditActivity.this, "更新失败");
                    break;
            }
        }
    };

    /**
     * 完成并保存
     */
    @Override
    public void rightOperation() {
        if (keyTimes.containsKey("right")) {
            if (System.currentTimeMillis() < keyTimes.get("right") + 1000) {
                keyTimes.put("right", System.currentTimeMillis());
                UIHelper.ToastMessage(this, "间隔较短，请稍后");
                return;
            }
        } else {
            keyTimes.put("right", System.currentTimeMillis());
        }
        pd.show();
        final UserInfo userInfo2 = getUserInfo();
        if (userInfo2 != null)
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    boolean up = userService.updateIndentity(userInfo2);
                    if (up) {
                        AppContext.getInstance().initUserInfo(userInfo2);
                        handler.sendEmptyMessage(SUCCESS);
                    } else {
                        handler.sendEmptyMessage(FAIL);
                    }

                }
            });
        pd.dismiss();

    }

    /**
     * 初始化界面
     */
    private void initView() {
        setTvTitle("编辑个人信息");
        cbBm = (CheckBox) findViewById(R.id.cb_user_edit_sex_bm);
        cbMan = (CheckBox) findViewById(R.id.cb_user_edit_sex_man);
        cbMale = (CheckBox) findViewById(R.id.cb_user_edit_sex_male);

        etNick = (EditText) findViewById(R.id.et_user_edit_nickname);
        etAge = (TextView) findViewById(R.id.et_user_edit_age);
        etSchool = (TextView) findViewById(R.id.et_user_edit_school);
        etMail = (EditText) findViewById(R.id.et_user_edit_mail);
        etHome = (TextView) findViewById(R.id.et_user_edit_home);
        etSign = (EditText) findViewById(R.id.et_user_edit_sign);
        etIntro = (EditText) findViewById(R.id.et_user_edit_introduction);

    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        etAge.setOnClickListener(this);
        etSchool.setOnClickListener(this);
        etHome.setOnClickListener(this);

        cbBm.setOnClickListener(this);
        cbMan.setOnClickListener(this);
        cbMale.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_user_edit_age:
                showAges();
                break;
            case R.id.et_user_edit_school:
                showSchools();
                break;
            case R.id.et_user_edit_home:
                showLocChoose();
                break;
            case R.id.cb_user_edit_sex_bm:
                checkSex(0);
                break;
            case R.id.cb_user_edit_sex_male:
                checkSex(1);
                break;
            case R.id.cb_user_edit_sex_man:
                checkSex(2);
                break;
        }
    }

    /**
     * 选择学校
     */
    private void showSchools() {
        final SchoolAlertDialog ad = new SchoolAlertDialog(UserEditActivity.this);
        ad.setTitle("选择所在学校");

        ad.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ad.getSelected() == null) {
                    UIHelper.ToastMessage(UserEditActivity.this, "您未做选择");
                } else {
                    etSchool.setText(ad.getSelected());
                }
                ad.dismiss();
            }
        });

        ad.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }


    /**
     * 选召唤类型
     */
    private void showAges() {
        final ListAlertDialog ad = new ListAlertDialog(UserEditActivity.this);
        ad.setTitle("选择出生时间");
        final String[] arr = this.getResources().getStringArray(R.array.user_age_years);
        ad.setArray(arr);
        ad.setOnFinishedListener(new ListAlertDialog.OnFinishedListener() {
            @Override
            public void finish(int input) {
                etAge.setText(arr[input]);
                age = input;
            }
        });
    }

    /**
     * 选择地区
     */
    private void showLocChoose() {
        final CityAlertDialog ad = new CityAlertDialog(UserEditActivity.this);
        ad.setTitle("选择家乡");

        ad.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ad.getSelected() == null) {
                    UIHelper.ToastMessage(UserEditActivity.this, "您未选择任何选项");
                } else {
                    System.out.println(ad.getSelected());
                    etHome.setText(ad.getSelected());
                }
                ad.dismiss();
            }
        });

        ad.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }

}
